#include "Thread.hpp"
#include "BlockQueue.hpp"
#include <vector>

// void Print(int a)
// {
//     int cnt = 10;
//     while(cnt--)
//     {
//         std::cout << "a = " << a << std::endl;
//         sleep(1);
//     }
// }

// int main()
// {
//     int a =10;
//     std::string name = "Thread-1";
//     std::function<void(int&)> f = Print;
//     Thread<int> thread(Print,a);
//     return 0;
// }
void productor(BlockQueue<int> &bq)//生产者执行的工作
{
    while (true)
    {
        int data = rand()%10;
        bq.Enqueue(data);
        std::cout << "enqueue seccess! data : " << data << std::endl;
    }
}
void consumer(BlockQueue<int> &bq)//消费者执行的工作
{
    int data;
    while(true)
    {
        bq.Pop(&data);
        std::cout << "Pop success! data : " << data << std::endl;
        sleep(1);
    }
}
void StartCommon(func_t<BlockQueue<int>> func, int num, std::vector<Thread<BlockQueue<int>>> &threads, BlockQueue<int> &bq)
{
    for (int i = 0; i < num; ++i)
    {
        std::string name = "thread-" + std::to_string(i + 1);
        threads.emplace_back(func, bq, name);
        sleep(1);
    }
}
void StartConsumer(int num, std::vector<Thread<BlockQueue<int>>> &threads, BlockQueue<int> &bq)
{
    StartCommon(consumer, num, threads, bq);
}
void StartProductor(int num, std::vector<Thread<BlockQueue<int>>> &threads, BlockQueue<int> &bq)
{
    StartCommon(productor, num, threads, bq);
}
void WaitAll(std::vector<Thread<BlockQueue<int>>> &threads)
{
    for (auto &thread : threads)
    {
        thread.Join();
    }
}

int main()
{
    BlockQueue<int> *_block = new BlockQueue<int>(10);//后续生产者和消费者看到的同一个阻塞队列
    int productor_num = 3; // 生产者个数
    int consumer_num = 5; //消费者个数
    std::vector<Thread<BlockQueue<int>>> threads;//管理所有的生产者和消费者
    StartProductor(productor_num, threads, *_block);//启动所有的生产者
    StartConsumer(consumer_num, threads,*_block);//启动所有的消费者
    WaitAll(threads);//等待所有线程
    return 0;
}